<?php
/**
 * Created by PhpStorm.
 * User: tom_xia
 * Date: 2018/5/24
 * Time: 10:18
 * 点赞入库
 */
require_once dirname(__DIR__)."/common.php";
use app\lib\db\DbException;
use app\cls\tom\Queue;
use app\cls\tom\SysResource;
use app\cls\tom\Process;

$process = new Process(__FILE__);
$process->setProcessNum(1);
$process->initProcess();
$redis = SysResource::getRedis();
$db =  SysResource::getDB(true);
$queue = new Queue($redis,REDIS_PREFIX."praise");
$queueNum = $queue->getQueueNum();
try{
    while(true){
        for($i = 0 ;$i< $queueNum;$i++){
            for($j = 0 ;$j < 100;$j++){
                $dataStr = $queue->pop($i);
                if(empty($dataStr)){
                    break;
                }
                echo $dataStr."\n";
                $data = json_decode($dataStr,true);
                if(is_array($data)){
                    foreach($data as $row){
                        if(!isset($row["id"]) || !isset($row["num"])){
                            continue;
                        }
                        $row["num"] = intval($row["num"]);
                        $db->update("user_material",["zan"=>"!zan+{$row["num"]}","order_zan"=>"!order_zan+{$row["num"]}"],["user_material_uuid"=>$row["id"]]);
                        $db->update("user_material",["custom_zan"=>"!custom_zan+{$row["num"]}"],["user_material_uuid"=>$row["id"],"custom_zan>"=>0]);
                        if(!empty($row["user_uuid"])){
                            $count = $db->from("user_praise")->where(["user_uuid"=>$row["user_uuid"],"material_uuid"=>$row["id"]])->count_all_results();
                            if($count == 0){
                                $db->insert("user_praise",[
                                    "user_uuid"=>$row["user_uuid"],
                                    "material_uuid"=>$row["id"],
                                    "add_time"=>date("Y-m-d H:i:s")
                                ]);
                            }
                        }
                    }
                }
            }
        }
//        sleep(5);
        sleep(1);
        $db->reconnect();
        $process->checkProcessTime(true);
    }
}catch (DBException $e){
    if(!empty($dataStr)){
        $queue->push($dataStr,1,"right");
    }
    $process->log($e->getMessage());
    $process->restartProcess();
}catch (Exception $e){

    $process->log($e->getMessage());
}